﻿using EquipSecs300;
using SecsEquip;
using SecsEquip300;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Runtime.ConstrainedExecution;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Xml.Linq;

namespace EquipSecs300
{
    public class GEM_Variables : SecsEquipEx
    {
        public string m_pViewName;
        Timer timer;
        public SePresentData SePresentDataRBArm1;
        public SePresentData SePresentDataRBArm2;
        public SePresentData SePresentDataAligner;
        public SePresentData SePresentDataInspST;
        DataTable EventReportDB;
        DataTable ReportVidDB;

        public GEM_Variables(CSecsEquip300 m_pSecs, SecsEquipHelper secsEquipHelper)
        {
            this.m_pSecs = m_pSecs;
            this.SecsEquipHelper = secsEquipHelper;
        }

        public override void UpdateData()
        {
            //timer = new Timer() { Interval = 200, Enabled = true };
            //timer.Elapsed += Timer_Elapsed;

            m_pSecs.m_pVarValueCallback += OnVariableValueHandler;
        }
        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            UpdataEvenTime();
        }

        // 增加到SECS
        void AddDataToSECS(int ID, string varName, string description, string varClass,
            string ValueType, string Value, string Units)
        {
            // 添加到Secs tool
            m_pSecs.VariableAdd(ID, varName, description, ValueType, Value, Units);
        }

        /// <summary>
        /// 根据VID设置变量值
        /// </summary>
        /// <param name="nVID"></param>
        /// <param name="newValue"></param>
        public void SetValue(int nVID, string newValue)
        {
            if (nVID != -1 && m_pSecs != null)
            {
                m_pSecs.VariableSet(nVID, newValue);
                //查询
                //GetValue(nVID, ref newValue);
            }
        }
        /// <summary>
        /// 根据名称设置变量值
        /// </summary>
        /// <param name="nVID"></param>
        /// <param name="newValue"></param>
        public void SetValue(string strName, string newValue)
        {
            int nVID = GetVIDByName(strName);
            SetValue(nVID, newValue);
        }

        // 获取最新值
        public void GetValue(int varID, ref string Value)
        {
            RcResult rc = m_pSecs.VariableGet(varID, ref Value);

            if (rc == 0)
            {

            }
        }

        List<VariableInfo> Variableinfo = null;
        /// <summary>
        /// 根据名称获取VID
        /// </summary>
        /// <returns></returns>
        public int GetVIDByName(string strName)
        {
            int nVID = -1;

            if (Variableinfo == null)
            {
                m_pSecs.VariableGetList(ref Variableinfo);
            }

            if (Variableinfo != null)
            {
                for (int i = 0; i < Variableinfo.Count; i++)
                {
                    if (strName.Equals(Variableinfo[i].Name))
                    {
                        nVID = UtilitiesConvert.StringToInt32(Variableinfo[i].VID);
                        return nVID;
                    }
                }
            }
            return nVID;
        }

        /// <summary>
        /// 以yyyyMMddHHmmssfff格式获取系统时间
        /// </summary>
        /// <returns></returns>
        public string GetCurrentTime()
        {
            string currentTime = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            return currentTime;
        }
        public void UpdataEvenTime()
        {
            SetValue(GetVIDByName("EVENTTIME"), GetCurrentTime());
        }

        // 设置变量回调
        public void SetValueCallBack(int nVID, OnVariableValueHandler onVariableValueHandler)
        {
            m_pSecs.VariableSetMethod(nVID, onVariableValueHandler);
        }
        /// <summary>
        /// 设置变量值,事件触发后关联的报表变量值通过回调获取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        [Description("委托方式获取变量")]
        public string OnVariableValueHandler(object sender, VariableValueEventArgs e)
        {
            string pValue = "";

            // 返回VID的值
            switch (e.VID)
            {
                case 10008:
                    {
                        GetValue(720, ref pValue);
                    }
                    break;
                case 10009:
                    {
                        GetValue(721, ref pValue);
                    }
                    break;

                #region
                case 90004:      // L数据类型(1层结构)
                    {

                        List<string> listData = new List<string>();
                        string nBarCode = CListOperate.listJoin("A", "123Code");     // 添加个子属性 
                        string pData2 = CListOperate.listJoin("A", "iik");     // 添加个子属性 
                        string pData3 = CListOperate.listJoin("HEX", "32EF29AX");     // 添加个子属性,HEX带的数据要偶数 

                        listData.Add("L");          // list数据
                        listData.Add(nBarCode);     // 跟随的子数据
                        listData.Add(pData2);     // 跟随的子数据
                        listData.Add(pData3);     // 跟随的子数据

                        pValue = CListOperate.listJoin(listData);
                    }
                    break;

                case 90005:      // L数据类型(2层结构)
                    {
                        //  L
                        //      L
                        //          A LOTIDA
                        //          A PROCESSIDA
                        //          A PRODUTA
                        //      L
                        //          A LOTIDB
                        //          A PROCESSIDB
                        //          A PRODUTB
                        //
                        List<string> listDataTopLevel = new List<string>();
                        List<string> listData1 = new List<string>();
                        List<string> listData2 = new List<string>();
                        string pLotID = CListOperate.listJoin("A", "lotA");     // 添加个子属性 
                        string pProcessID = CListOperate.listJoin("A", "proceeIDA");     // 添加个子属性 
                        string pProdutID = CListOperate.listJoin("A", "ProdutA");     // 添加个子属性 

                        // 1子层的内容 
                        listData1.Add("L");          // list数据
                        listData1.Add(pLotID);     // 跟随的子数据
                        listData1.Add(pProcessID);       // 跟随的子数据
                        listData1.Add(pProdutID);       // 跟随的子数据

                        pLotID = CListOperate.listJoin("A", "lotB");     // 添加个子属性 
                        pProcessID = CListOperate.listJoin("A", "proceeIDB");     // 添加个子属性 
                        pProdutID = CListOperate.listJoin("A", "ProdutB");     // 添加个子属性 

                        // 2子层的内容 
                        listData1.Add("L");          // list数据
                        listData1.Add(pLotID);     // 跟随的子数据
                        listData1.Add(pProcessID);       // 跟随的子数据
                        listData1.Add(pProdutID);       // 跟随的子数据

                        // 顶层的内容
                        listDataTopLevel.Add("L");
                        //    listDataTopLevel.Add(CListOperate.listJoin(listData1));
                        //     listDataTopLevel.Add(CListOperate.listJoin(listData2));

                        pValue = CListOperate.listJoin(listDataTopLevel);
                    }
                    break;
                    #endregion

            }

            return pValue;
        }
        public DataTable GetCsvfile(string strPath, int colLenth = -1)
        {
            CsvHelper csv = new CsvHelper(strPath);
            DataTable dt = csv.ReadCsvFile(colLenth);
            return dt;
        }
        public List<int> GetVIDList(int nStart, int nEnd)
        {
            int VIDTemp;
            List<int> nVIDArray = new List<int>();
            List<int> nVIDArrayRet = new List<int>();
            DataTable dt = GetCsvfile(Environment.CurrentDirectory + "\\JngServer\\SecsConfig\\SV.csv", 8);
            foreach (DataRow row in dt.Rows)
            {
                VIDTemp = Convert.ToInt32(row.ItemArray[0]);
                nVIDArray.Add(VIDTemp);
            }
            IEnumerable eVIDArray = nVIDArray.Where(x => x >= nStart && x <= nEnd).Select(x => x);

            foreach (int n in eVIDArray)
            {
                nVIDArrayRet.Add(n);
            }
            nVIDArrayRet.ToList();
            return nVIDArrayRet;
        }
        public int GetVIDIndex(int nOffset, List<int> nVIDArray)
        {
            for (int i = 0; i < nVIDArray.Count; i++)
            {
                if (nVIDArray[i] == nOffset)
                {
                    return i;
                }
            }
            return -1;
        }

        public DataTable EventReportCsv()
        {
            if (EventReportDB == null)
            {
                EventReportDB = GetCsvfile(Environment.CurrentDirectory + "\\JngServer\\SecsConfig\\EventReport.csv", 8);
            }
            return EventReportDB;
        }
        public List<int> GetRPTIDByCEID(int CEID)
        {
            List<int> listCEID = new List<int>();
            DataTable dt = EventReportCsv();
            foreach (DataRow row in dt.Rows)
            {
                if (UtilitiesConvert.StringToInt32(row.ItemArray[0].ToString()) == CEID)
                {
                    for (int i = 1; i < row.ItemArray.Length; i++)
                    {
                        listCEID.Add(UtilitiesConvert.StringToInt32(row.ItemArray[i].ToString()));
                    }
                }
            }
            return listCEID;
        }
        public bool IsContainRPTID(int CEID, int intRPTID)
        {
            List<int> listCEID = GetRPTIDByCEID(CEID);
            foreach (var item in listCEID)
            {
                if (item == intRPTID)
                {
                    return true;
                }
            }
            return false;
        }


        public DataTable ReportVidCsv()
        {
            if (ReportVidDB == null)
            {
                ReportVidDB = GetCsvfile(Environment.CurrentDirectory + "\\JngServer\\SecsConfig\\ReportVid.csv", 10);
            }
            return ReportVidDB;
        }

        public List<int> GetVIDByRPTID(int RPTID)
        {
            List<int> listRPTID = new List<int>();
            DataTable dt = ReportVidCsv();
            foreach (DataRow row in dt.Rows)
            {
                if (UtilitiesConvert.StringToInt32(row.ItemArray[0].ToString()) == RPTID)
                {
                    for (int i = 1; i < row.ItemArray.Length; i++)
                    {
                        listRPTID.Add(UtilitiesConvert.StringToInt32(row.ItemArray[i].ToString()));
                    }
                }
            }
            return listRPTID;
        }
        public bool IsContainVID(int CEID, int intVID)
        {
            List<int> listVID = new List<int>();
            List<int> listRPTID = GetRPTIDByCEID(CEID);
            for (int i = 0; i < listRPTID.Count; i++)
            {
                listVID = GetVIDByRPTID(listRPTID[i]);
                for (int j = 0; j < listVID.Count; j++)
                {
                    if (listVID[j].ToString() == "")
                    {
                        break;
                    }
                    if (listVID[j] == intVID)
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        /// <summary>
        /// 更新工位资料 RB_ARM1_WAFER_DATA
        /// </summary>
        public void SetValue_PresentData_RBARM1()
        {
            SetValue(10410, SePresentDataRBArm1.WAFERID);
            SetValue(10411, SePresentDataRBArm1.WAFER_ST.ToString());
            SetValue(10412, SePresentDataRBArm1.PORTNO.ToString());
            SetValue(10413, SePresentDataRBArm1.SLOTNO.ToString());
            SetValue(10414, SePresentDataRBArm1.WFRESULT.ToString());
        }
        public void SetValue_PresentData_RBARM2()
        {
            SetValue(10420, SePresentDataRBArm2.WAFERID);
            SetValue(10421, SePresentDataRBArm2.WAFER_ST.ToString());
            SetValue(10422, SePresentDataRBArm2.PORTNO.ToString());
            SetValue(10423, SePresentDataRBArm2.SLOTNO.ToString());
            SetValue(10424, SePresentDataRBArm2.WFRESULT.ToString());
        }
        public void SetValue_SePresentDataAligner()
        {
            SetValue(10430, SePresentDataAligner.WAFERID);
            SetValue(10431, SePresentDataAligner.WAFER_ST.ToString());
            SetValue(10432, SePresentDataAligner.PORTNO.ToString());
            SetValue(10433, SePresentDataAligner.SLOTNO.ToString());
            SetValue(10434, SePresentDataAligner.WFRESULT.ToString());
        }
        public void SetValue_SePresentDataInspST()
        {
            SetValue(10440, SePresentDataInspST.WAFERID);
            SetValue(10441, SePresentDataInspST.WAFER_ST.ToString());
            SetValue(10442, SePresentDataInspST.PORTNO.ToString());
            SetValue(10443, SePresentDataInspST.SLOTNO.ToString());
            SetValue(10444, SePresentDataInspST.WFRESULT.ToString());
        }
        private void SetValue_InspRes_Common()
        {
            SetValue_SePresentDataInspST();
            SetValue(10350, SePresentDataInspST.SeInspCommonItem.PPID);
            SetValue(10201, SePresentDataInspST.SeInspCommonItem.PortFoupID);
            SetValue(10651, SePresentDataInspST.SeInspCommonItem.CHECK_POINT_X_POS.ToString());
            SetValue(10652, SePresentDataInspST.SeInspCommonItem.CHECK_POINT_Y_POS.ToString());
        }

        [Obsolete]
        public void SetValue_InspRes(int inspCount, Dictionary<string, string> DicInspRes)
        {
            SetValue_InspRes_Common();
            int offsetVID = 10661;
            int nVID = offsetVID;
            foreach (var item in DicInspRes)
            {
                SetValue(nVID, item.Key);
                SetValue(nVID, item.Value);
                nVID++;
                if (nVID == inspCount)
                {
                    break;
                }
            }
        }

        public void SetPresentValue(WorkStation_KE workStation_KE, SePresentData sePresentData)
        {
            int nOffsetVID = (int)workStation_KE;
            SetValue(10410 + nOffsetVID, sePresentData.WAFERID);
            SetValue(10411 + nOffsetVID, sePresentData.WAFER_ST.ToString());
            SetValue(10412 + nOffsetVID, sePresentData.PORTNO.ToString());
            SetValue(10413 + nOffsetVID, sePresentData.SLOTNO.ToString());
            SetValue(10414 + nOffsetVID, sePresentData.WFRESULT.ToString());
            SetValue(10415 + nOffsetVID, sePresentData.WAFERID_Lot.ToString());

            if (string.IsNullOrEmpty(sePresentData.WAFERID))
            {
                LogVIDMsg($"Work Station: {workStation_KE.ToString()}, WaferID Is Empty");
            }
        }

        /// <summary>
        /// 将检测结果Dictionary类型转化为string类型（SV.cs列表对应TYPE需为L）
        /// </summary>
        /// <param name="InspectRes"></param>
        /// <returns></returns>
        public string ListJoinInspRes(Dictionary<string, List<double>> InspectRes)
        {
            if (InspectRes == null) return "";
            List<string> listData = new List<string>();
            listData.Add("L");
            foreach (var item in InspectRes)
            {
                string name = CListOperate.listJoin("A", item.Key);
                listData.Add(name);
                foreach (var subItem in item.Value)
                {
                    string data = CListOperate.listJoin("A", subItem.ToString());
                    listData.Add(data);
                }
            }
            string strRes = CListOperate.listJoin(listData);
            return strRes;
        }

        private void LogVIDMsg(string log)
        {
            LogMsg("变量: " + log, MsgSource_KE.EQ);
        }
    }
}
